package com.openlogic.common.plugins.db.api.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.openlogic.common.plugins.spi.constants.CommonConstants;

/**
 * @ClassName: ImmutablePropertyDelegate
 * @Description: 不可变property属性委托器
 * @author weiyongpeng
 * @date 2024年11月16日 上午8:58:19
 */
public class ImmutablePropertyDelegate implements IPropertyDelegate {

	private static final Logger log = LoggerFactory.getLogger(ImmutablePropertyDelegate.class);

	private final Properties properties;

	public ImmutablePropertyDelegate() {
		this(CommonConstants.COMMON_PROPERTIES_PATH);
	}

	public ImmutablePropertyDelegate(String... propertyAbsolutePath) {
		properties = new Properties();
		// read from classpath
		for (String fileName : propertyAbsolutePath) {
			try (InputStream fis = getClass().getResourceAsStream(fileName)) {
				Properties subProperties = new Properties();
				subProperties.load(fis);
				properties.putAll(subProperties);
			} catch (IOException e) {
				log.error("Load property: {} error, please check if the file exist under classpath",
						propertyAbsolutePath, e);
				System.exit(1);
			}
		}
		printProperties();
	}

	public ImmutablePropertyDelegate(Properties properties) {
		this.properties = properties;
	}

	@Override
	public String get(String key) {
		return properties.getProperty(key);
	}

	@Override
	public String get(String key, String defaultValue) {
		return properties.getProperty(key, defaultValue);
	}

	@Override
	public Set<String> getPropertyKeys() {
		return properties.stringPropertyNames();
	}

	private void printProperties() {
		properties.forEach((k, v) -> log.debug("Get property {} -> {}", k, v));
	}

}
